import 'dart:io';

import 'package:app_admin/utils/HttpUtil.dart';
import 'package:app_admin/utils/logger.dart';
import 'package:app_admin/utils/data_sp.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:path_provider/path_provider.dart';

class Config {
  static Future init(Function() runApp) async {
    WidgetsFlutterBinding.ensureInitialized();
    try {
      cachePath = (await getApplicationDocumentsDirectory()).path; //缓存路径
      await DataSp.init();
      await Hive.initFlutter(cachePath);

      HttpUtil.init();
    } catch (_) {}

    runApp();

    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);

    var brightness = Platform.isAndroid ? Brightness.dark : Brightness.light;
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarBrightness: brightness,
      statusBarIconBrightness: brightness,
    ));
  }

  ///缓存路径
  static late String cachePath;

  static const uiW = 375.0;
  static const uiH = 812.0;
  static const double textScaleFactor = 1.0;

  static const _host = "203.56.175.233";
  static const _ipRegex =
      '((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)';
  static bool get _isIP => RegExp(_ipRegex).hasMatch(_host);

  ///服务器地址
  static String get apiUrl {
    String? url;
    var server = DataSp.getServerConfig();
    if (null != server) {
      url = server['apiUrl'];
      Logger.print('缓存apiUrl: $url');
    }
    return url ?? (_isIP ? 'http://$_host:10002' : "https://$_host/api");
  }

  static String get appAuthUrl {
    String? url;
    var server = DataSp.getServerConfig();
    if (null != server) {
      url = server['authUrl'];
      Logger.print('缓存authUrl: $url');
    }
    return url ?? (_isIP ? "http://$_host:10008" : "https://$_host/chat");
  }
}
